#include <gtest/gtest.h>
#include "../../common/sys_file.h"
#include "../../common/log.h"

TEST(SysFileTest, OpenExistFile)
{
	asce::SysFile sys_file;
	EXPECT_TRUE(sys_file.Open("test.txt"));
	EXPECT_TRUE(sys_file.valid());
}

TEST(SysFileTest, OpenUnExistFile)
{
	asce::SysFile sys_file;
	EXPECT_FALSE(sys_file.Open("unexist.txt"));
	EXPECT_FALSE(sys_file.valid());
}

TEST(SysFileTest, OpenMoreTimes)
{
	asce::SysFile sys_file;
	EXPECT_TRUE(sys_file.Open("test.txt"));
	EXPECT_TRUE(sys_file.valid());
	EXPECT_FALSE(sys_file.Open("test.txt"));
	EXPECT_TRUE(sys_file.valid());
}

TEST(SysFileTest, CreatUnexistFile)
{
	asce::SysFile sys_file;
	EXPECT_TRUE(sys_file.Creat("creatfile.txt"));
	EXPECT_TRUE(sys_file.valid());
	EXPECT_TRUE(sys_file.Delete());
}

TEST(SysFileTest, CreatExistFile)
{
	asce::SysFile sys_file;
	EXPECT_FALSE(sys_file.Creat("test.txt"));
	EXPECT_FALSE(sys_file.valid());
	EXPECT_FALSE(sys_file.Delete());
}

TEST(SysFileTest, CreatMoreTimes)
{
	asce::SysFile sys_file;
	EXPECT_TRUE(sys_file.Creat("creatmorefime.txt"));
	EXPECT_TRUE(sys_file.valid());
	EXPECT_FALSE(sys_file.Creat("test.txt"));
	EXPECT_TRUE(sys_file.valid());
	EXPECT_TRUE(sys_file.Delete());
}

TEST(SysFileTest, CloseUnOpenFile)
{
	asce::SysFile sys_file;
	EXPECT_TRUE(sys_file.Close());
}

TEST(SysFileTest, CloseOpenedFile)
{
	asce::SysFile sys_file;
	EXPECT_TRUE(sys_file.Open("test.txt"));
	EXPECT_TRUE(sys_file.valid());
	EXPECT_TRUE(sys_file.Close());
}

TEST(SysFileTest, ReadInvalidParam)
{
	char buffer[1024] = {0};

	asce::SysFile sys_file;
	EXPECT_TRUE(sys_file.Open("test.txt"));
	EXPECT_EQ(-1, sys_file.Read(NULL, 10));
	EXPECT_EQ(-1, sys_file.Read(buffer, 0));
}

TEST(SysFileTest, ReadUnOpenedFile)
{
	char buffer[512] = {0};
	
	asce::SysFile sys_file;
	EXPECT_EQ(-1, sys_file.Read(buffer, 512));
}

TEST(SysFileTest, WriteInvalidParam)
{
	char buffer[] = "test";

	asce::SysFile sys_file;
	EXPECT_TRUE(sys_file.Open("test.txt"));
	EXPECT_EQ(-1, sys_file.Write(NULL, 10));
	EXPECT_EQ(-1, sys_file.Write(buffer, 0));
}

TEST(SysFileTest, WriteUnOpenFile)
{
	char buffer[] = "test";
	
	asce::SysFile sys_file;
	EXPECT_EQ(-1, sys_file.Write(buffer, sizeof(buffer)));
}

TEST(SysFileTest, CopyFile)
{
	asce::SysFile source_file;
	EXPECT_TRUE(source_file.Open("test.txt"));

	asce::SysFile dest_file;
	EXPECT_TRUE(dest_file.Creat("dst.txt"));

	char buf[512] = {0};
	ssize_t res = 0;
	while (true)
	{
		res = source_file.Read(buf, 511);
		if (-1 == res)
		{
			break;
		}

		if (0 == res)
		{
			asce::Log::Instance().Write(asce::LOG_INFO, "CopyFileByOneChar Source file end");
			break;
		}

		res = dest_file.Write(buf, res);
		if (-1 == res)
		{
			break;
		}
	}
}


int main(int argc, char** argv)
{
	testing::InitGoogleTest(&argc, argv);
	return RUN_ALL_TESTS();
}
